package com.traitswu.websocket.dmxlog;

import org.apache.commons.io.IOUtils;

import javax.script.*;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xiaoquan on 17-5-27.
 */
public class ScriptExecuteUtils {


    private static Map<String, CompiledScript> scripts = new HashMap<>();


    private static String loadScript(String path) throws Exception {
        InputStream stream = ScriptExecuteUtils.class.getClassLoader().getResourceAsStream(path);
        return IOUtils.toString(stream, Charset.forName("UTF-8"));
    }


    static {
        try {
            String script1 = loadScript("action1.groovy");
            String script2 = loadScript("action2.groovy");

            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("groovy");

            CompiledScript compiledScript1 = ((Compilable) engine).compile(script1);
            CompiledScript compiledScript2 = ((Compilable) engine).compile(script2);

            scripts.put("action1", compiledScript1);
            scripts.put("action2", compiledScript2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    public static Object eval(String scriptId, Map<String, Object> params) throws Exception {
        SimpleBindings bindings = new SimpleBindings();
        bindings.putAll(params);
        return scripts.get(scriptId).eval(bindings);
    }


}
